ASP.NET ViewState

Another viewpoint for saving the data for the user is the viewstate, as described in this tutorial elsewhere, the viewstat allows ASP.NET to reconsider the form field on each postback on the server, to ensure that That when a user hits the submit button, a form is not automatically cleared. All this happens automatically, until you turn it off, but you can actually use ViewStat for your own purposes. Please keep in mind that while cookies and sessions can be accessed from all your pages on your website, viewStat values ​​are not made between pages. Here is a simple example of using ViewState to move values ​​between postbacks:


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>ViewState</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:TextBox runat="server" id="NameField" />
        <asp:Button runat="server" id="SubmitForm" onclick="SubmitForm_Click" text="Submit & set name" />
        <asp:Button runat="server" id="RefreshPage" text="Just submit" />
        <br /><br />
        Name retrieved from ViewState: <asp:Label runat="server" id="NameLabel" />
    </form> 
</body>
</html>

And the CodeBehind:


using System;
using System.Data;
using System.Web;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(ViewState["NameOfUser"] != null)
            NameLabel.Text = ViewState["NameOfUser"].ToString();
        else
            NameLabel.Text = "Not set yet...";
    }

    protected void SubmitForm_Click(object sender, EventArgs e)
    {
        ViewState["NameOfUser"] = NameField.Text;
        NameLabel.Text = NameField.Text;
    }
}

Try to run the project, enter your name in the text box and press the first button the name will be saved in the viewtest and also set to the label. There is no magic at all. Now press the second button. It does not really do anything, it only posts back to the server.

As you will see, the name label still has the name, but the text box is the same. The first thing is that by us, while the textbox has been retained by ASP.NET. Try to remove the value and press the second button again. You will see that the text box is now approved, but our name keeps the label's name, because the saved value of the viewstate is still there!

Very easy to store simple values ​​for use in the viewstate form, but if you want to save more complex data, and keep them from page to page, you can use cookies or sessions described in previous chapters. should do.